<template>
    <el-form ref="form" :model="localUser" :rules="rules" label-width="80px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="localUser.nickName" maxlength="30" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="localUser.phonenumber" maxlength="11" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="localUser.email" maxlength="50" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="localUser.sex">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="submit" :loading="loading">保存</el-button>
        <el-button type="danger" size="mini" @click="close">关闭</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script>
  import { updateUserProfile } from "@/api/system/user";
  
  export default {
    props: {
      user: {
        type: Object,
        default: () => ({}) // 提供默认值
      }
    },
    data() {
      return {
        localUser: {}, // 使用本地副本进行编辑
        loading: false,
        // 表单校验规则
        rules: {
          nickName: [
            { required: true, message: "用户昵称不能为空", trigger: "blur" }
          ],
          email: [
            { required: true, message: "邮箱地址不能为空", trigger: "blur" },
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"]
            }
          ],
          phonenumber: [
            { required: true, message: "手机号码不能为空", trigger: "blur" },
            {
              // 注意：这里的正则可能需要根据实际手机号规则调整
              pattern: /^1[3-9]\d{9}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ]
        }
      };
    },
    watch: {
      // 监听 props.user 的变化，更新本地副本
      user: {
        handler(newUser) {
          // 深拷贝，避免直接修改 prop
          this.localUser = JSON.parse(JSON.stringify(newUser || {}));
        },
        immediate: true, // 立即执行一次
        deep: true
      }
    },
    methods: {
      submit() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.loading = true;
            updateUserProfile(this.localUser).then(() => {
              this.$modal.msgSuccess("修改成功");
              // 通知父组件更新信息
              this.$emit('profileUpdated');
            }).finally(() => {
              this.loading = false;
            });
          }
        });
      },
      close() {
        // 可以添加关闭或返回逻辑
         this.$router.go(-1); // 示例：返回上一页
         // 或者可以关闭 tab/modal (如果是在弹窗内)
         // this.$store.dispatch("tagsView/delView", this.$route);
         // this.$router.push({ path: "/index" });
      }
    }
  };
  </script>